package com.yh.zz_hlj.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.google.gson.Gson;
import com.yh.zz_hlj.AppConfig;
import com.yh.zz_hlj.AppContext;
import com.yh.zz_hlj.R;
import com.yh.zz_hlj.api.ErrorHandler;
import com.yh.zz_hlj.api.RetrofitSingleton;
import com.yh.zz_hlj.base.BaseFragment;
import com.yh.zz_hlj.common.FullyLinearLayoutManager;
import com.yh.zz_hlj.common.MyScrollview;
import com.yh.zz_hlj.common.PLog;
import com.yh.zz_hlj.common.StringUtils;
import com.yh.zz_hlj.common.TDevice;
import com.yh.zz_hlj.common.Time;
import com.yh.zz_hlj.common.UIHelper;
import com.yh.zz_hlj.modules.adatper.InOrOutStockAdapter;
import com.yh.zz_hlj.modules.bean.CM;
import com.yh.zz_hlj.modules.bean.CardStockEntry;
import com.yh.zz_hlj.modules.bean.CardXSCKEntry;
import com.yh.zz_hlj.modules.bean.CustPhone;
import com.yh.zz_hlj.modules.bean.Result;
import com.yh.zz_hlj.modules.bean.SimpleBackPage;
import com.yh.zz_hlj.modules.bean.XsckHeadStockEntry;
import com.yh.zz_hlj.modules.widget.RecycleViewDivider;
import com.yh.zz_hlj.print.Activity_Main;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.zz_hlj.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * =========================o
 * 版权所有，违法必究
 * 作者：john
 * <p>
 * 工程：ZZVComApp
 * <p>
 * 文件名：OutStockFragment
 * <p>
 * 创建时间：2017.06.19.11:53
 * *****************************
 */
public class OutStockFragment extends BaseFragment {


    @InjectView(R.id.tv_date)
    TextView tvDate;
    @InjectView(R.id.ll_date)
    LinearLayout llDate;
    @InjectView(R.id.tv_CkOrder)
    EditText tvCkOrder;
    @InjectView(R.id.tv_CkType)
    TextView tvCkType;
    @InjectView(R.id.ll_Customer)
    LinearLayout llCustomer;
    @InjectView(R.id.tv_batch)
    EditText tvBatch;
    @InjectView(R.id.recyclerview)
    RecyclerView mRecycleview;
    @InjectView(R.id.scrollview)
    MyScrollview scrollview;

    private InOrOutStockAdapter mAdapter;
    private ArrayList<CardStockEntry> mDatas;
    private CardStockEntry mCardStockEntry;
    private boolean isSave;
    private XsckHeadStockEntry cardHeadStockEntry;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                if (result.getStatusCode() == 200) {
                    Gson gson = new Gson();
                    Object objects = result.getData();
                    if (objects != null) {
                        String json = gson.toJson(objects);
                        try {
                            JSONObject jo = new JSONObject(json);
//                            final String fBillNo = jo.optString("FBillNo");
                            final String fXinHao = jo.optString("FXinHao");
                            final String fBanBen = jo.optString("FBanBen");
                            final String fItem = jo.optString("FItem");
                            final String fQty = jo.optString("FQty");

                            Intent intent = new Intent(mActivity, Activity_Main.class);
                            intent.putExtra("OutStock", "OutStock");

                            String[] str = new String[4];
                            str[0] = fXinHao;
                            str[1] = fBanBen;
                            str[2] = fItem;
                            str[3] = fQty;
//                            str[4] = fBillNo;

                            intent.putExtra("FOUT", str);

                            mActivity.startActivity(intent);
                            mActivity.finish();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                handleOtherText(message);
            }
        }
    };
    private CardStockEntry mCardStockEntry1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_back_mat, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    private void handleOtherText(final String text) {
        try {
            if (StringUtils.isChinese(text)) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "请确认扫描是否正确 !", Snackbar.LENGTH_SHORT).show();
            } else {
                if (StringUtils.isDigit(text)) {
                    mCardStockEntry1 = new CardStockEntry();
                    if (mDatas != null && mDatas.size() > 0) {
                        for (int i = 0; i < mDatas.size(); i++) {
                            String fNumber = mDatas.get(i).getFNumber();

                            if (fNumber.equals(text)) {
                                Snackbar.make(mActivity.getWindow().getDecorView(), "请确认是否添加过该单据 !", Snackbar.LENGTH_SHORT).show();
                                return;
                            }
                        }
                    }
                    mCardStockEntry1.setFNumber(text); //1
                    mCardStockEntry1.setFType("1");
                    mDatas.add(mCardStockEntry1);
                } else {
                    JSONObject jo = new JSONObject(text);
                    final String number = jo.optString("箱号");
                    final String type = jo.optString("FType");

//                    Gson gson = new Gson();
//                    mCardStockEntry = gson.fromJson(text, CardStockEntry.class);
//
//                    String number = mCardStockEntry.getFNumber();
//                    String type = mCardStockEntry.getFType();

                    if (mDatas != null && mDatas.size() > 0) {
                        for (int i = 0; i < mDatas.size(); i++) {
                            String fNumber = mDatas.get(i).getFNumber();
                            String fType = mDatas.get(i).getFType();

                            if (fNumber.equals(number) && fType.equals(type)) {
                                Snackbar.make(mActivity.getWindow().getDecorView(), "请确认是否添加过该单据 !", Snackbar.LENGTH_SHORT).show();
                                return;
                            }
                        }
                    }

                    mCardStockEntry.setFNumber(number); //1
                    mCardStockEntry.setFType(type);
                    mDatas.add(mCardStockEntry);
                }
            }
            //0代表入库，1代表出库
            mAdapter = new InOrOutStockAdapter(mActivity, mDatas, "1");
            mRecycleview.setAdapter(mAdapter);

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    scrollview.fullScroll(ScrollView.FOCUS_DOWN);
                }
            });
        } catch (Exception e) {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请确认是否扫描正确！", Snackbar.LENGTH_SHORT).show();
        }
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        isSave = false;
        tvDate.setText(Time.getNowYMDHMSTime());

        TDevice.hideSoftKeyboard(mActivity);
        setHasOptionsMenu(true);
        mDatas = new ArrayList<>();
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(getContext());
        mRecycleview.setNestedScrollingEnabled(false);
        mRecycleview.setLayoutManager(layoutManager);
        mRecycleview.addItemDecoration(new RecycleViewDivider(mActivity, LinearLayoutManager.VERTICAL));
        mRecycleview.setItemAnimator(new DefaultItemAnimator());
        mRecycleview.setHasFixedSize(true);


        //关联ItemTouchHelper和RecyclerView
//        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mAdapter);
//        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
//        itemTouchHelper.attachToRecyclerView(mRecycleview);

    }

    @Override
    public void initData() {
        super.initData();
        mCardStockEntry=new CardStockEntry();
         cardHeadStockEntry = new XsckHeadStockEntry();

        llDate.setOnClickListener(this);
        llCustomer.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_date:
                new SlideDateTimePicker.Builder(getFragmentManager())
                        .setListener(listener)
                        .setInitialDate(new Date())
                        .build()
                        .show();
                break;
            case R.id.ll_Customer:
                bundle.putString("type", "cklx");
                UIHelper.showSimpleBackForResult(this, mActivity, 0, SimpleBackPage.CUST_PHEON, bundle, "出库类型");
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                String id = item.getId();
                switch (requestCode) {
                    case 0:
                        tvCkType.setText(item.getName());
                        cardHeadStockEntry.setFOutStockType(id);
                        break;
                }
            }
        }
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.send_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                if (mDatas != null && mDatas.size() > 0) {
                    if (!StringUtils.isEmpty(tvCkOrder.getText().toString())) {
                        subMat();
                    } else {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "请输入销售出库单号 !", Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "请先扫描单据 !", Snackbar.LENGTH_SHORT).show();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //提交方法
    private void subMat() {
        //表头

        String date = tvDate.getText().toString();
        String batch = tvBatch.getText().toString();
        String mTvCkOrder = tvCkOrder.getText().toString();

        cardHeadStockEntry.setFDate(date);
        cardHeadStockEntry.setFBatch(batch);
        cardHeadStockEntry.setFNumber(mTvCkOrder);
        //表体
        List<CardStockEntry> bodys = new ArrayList<>();

        for (int i = 0; i < mDatas.size(); i++) {
            CardStockEntry cardStockEntry = new CardStockEntry();
            String fNumber = mDatas.get(i).getFNumber();
            String fType = mDatas.get(i).getFType();
            cardStockEntry.setFNumber(fNumber);
            cardStockEntry.setFType(fType);

            bodys.add(cardStockEntry);
        }

        showWaitDialog();
        CardXSCKEntry matSubBean = new CardXSCKEntry();
        matSubBean.setBodyList(bodys);
        matSubBean.setHeadDetail(cardHeadStockEntry);
        Gson gson = new Gson();
        String json = gson.toJson(matSubBean);
        String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
        CM cm = new CM();
        cm.setToken(token);
        cm.setData(json);
        RetrofitSingleton.getApiService(mActivity).
                OutStockSubmit(cm)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private SlideDateTimeListener listener = new SlideDateTimeListener() {
        @Override
        public void onDateTimeSet(Date date) {
            String str = StringUtils.getDateString(date);
            tvDate.setText(str);
        }

        @Override
        public void onDateTimeCancel() {
        }
    };

}
